#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Person 
{
    char name[64];
    int age;
};

void test01()
{
    struct Person person1 = {"aaa",20};
    struct Person person2 = {"aaa",30};

    //结构体赋值
    person2 = person1;

    printf("Name:%s Age:%d\n", person1.name, person1.age);
    printf("Name:%s Age:%d\n", person2.name, person2.age);
}

struct Teacher 
{
    char *name;
    int age;
};

void test02()
{
    struct Teacher teacher1;
    teacher1.name = malloc(sizeof(char)*64);
    memset(teacher1.name, 0, 64);
    strcpy(teacher1.name, "aaa");
    teacher1.age = 20;

    struct Teacher teacher2;
    teacher2.name = malloc(sizeof(char)*128);
    memset(teacher2.name, 0, 128);
    strcpy(teacher2.name, "bbbbbbbbbbbbbbbbb");
    teacher2.age = 30;

    printf("Name:%s Age:%d\n", teacher1.name, teacher1.age);
    printf("Name:%s Age:%d\n", teacher2.name, teacher1.age);

    //赋值操作
    //不使用默认的结构体赋值
    //teacher1 = teacher2;
    //如果结构体内部有指针,并且指针指向堆空间, 那么会产生两个问题
    //1.同一块空间被释放两次
    //2.内存泄漏

    //如果结构体内部有指针,那么就不能使用编译器默认的赋值行为,应该手动控制赋值过程
    //1.先要释放调teahcer1的内存空间
    if(teacher1.name != NULL)
    {
        free(teacher1.name);
        teacher1.name = NULL;
    }
    //2.还不能直接等号操作,考虑到可能数据存不了那么大,按照数值的实际大小新申请一块空间
    teacher1.name = malloc(strlen(teacher2.name)+1);
    strcpy(teacher1.name, teacher2.name);
    teacher1.age = teacher2.age;

    printf("Name:%s Age:%d\n", teacher1.name, teacher1.age);
    printf("Name:%s Age:%d\n", teacher2.name, teacher1.age);

    if(teacher1.name != NULL)
    {
        free(teacher1.name);
        teacher1.name = NULL;
    }

     if(teacher2.name != NULL)
    {
        free(teacher2.name);
        teacher2.name = NULL;
    }
}

int main(int argc, char const *argv[])
{
    //test01();
    test02();
    return 0;
}
